package com.heima.canal.entry;

import com.heima.article.ApArticleFeign;
import com.heima.dfs.DfsFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.sun.org.apache.bcel.internal.generic.NEW;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@CanalTable("ap_article")
public class ArticleEntry implements EntryHandler<ApArticle> {
    @Autowired
    private DfsFeign dfsFeign;

    @Autowired
    private ApArticleFeign apArticleFeign;

    @Autowired
    private Configuration configuration;


    /**
     * 当article表添加一条记录
     * @param apArticle
     */
    @SneakyThrows
    @Override
    public void insert(ApArticle apArticle) {
        createStaticHtml(apArticle);
    }

    @SneakyThrows
    @Override
    public void update(ApArticle before, ApArticle after) {

        if (before.getIsDown() == 0 && after.getIsDown() == 1){   //文章进行了下架操作
            deleteStaticHtml(after);
        }
        if (before.getIsDown() == 1 && after.getIsDown() == 0){   //文章进行了上架操作
            createStaticHtml(after);
        }
    }

    @Override
    public void delete(ApArticle apArticle) {
        deleteStaticHtml(apArticle);
    }

    /**
     * 生成静态页
     *
     */
    public void createStaticHtml(ApArticle apArticle) throws Exception{
        //1. 读取生成模板对象
        Template template = configuration.getTemplate("article.ftl");
        //2. 准备数据模型
        Map<String , Object> dataMap = new HashMap<>();
        dataMap.put("article" , apArticle);
        //3. 生成静态页(字符串格式/html文件格式)
        //template.process(dataMap , new PrintWriter("D:/1.html"));
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, dataMap);
        //4.feign远程调用dfs微服务上传文件
        ResponseResult<Map<String, Object>> uploadHtml = dfsFeign.uploadHtml(content, "html");
        String staticUrl = uploadHtml.getData().get("url").toString();
        //5.feign远程远程调用article微服务添加ap_article表静态页地址
        ApArticle after = new ApArticle();
        after.setId(apArticle.getId());
        after.setStaticUrl(staticUrl);
        apArticleFeign.update(after);
    }

    /**
     * 删除静态页
     */
    public void deleteStaticHtml(ApArticle apArticle){
        //1.删除文章表静态页地址
        apArticleFeign.delete(apArticle.getId());
        //2.删除dfs静态页文件
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("url" , apArticle.getStaticUrl());
        dfsFeign.deleteHtml(requestParam);
    }



}
